﻿namespace Away.Common.Mvc.Logger;

/// <summary>
/// 收集异常日志
/// </summary>
public class ExceptionLoggerAttribute : ServiceFilterAttribute
{
    public ExceptionLoggerAttribute() : base(typeof(ExceptionLoggerIAsyncExceptionFilter))
    {
    }
}

[ServiceInject(ServiceLifetime.Scoped, true)]
public class ExceptionLoggerIAsyncExceptionFilter : IAsyncExceptionFilter
{
    private readonly ILogger<ExceptionLoggerIAsyncExceptionFilter> _logger;
    public ExceptionLoggerIAsyncExceptionFilter(ILogger<ExceptionLoggerIAsyncExceptionFilter> logger)
    {
        _logger = logger;
    }

    public async Task OnExceptionAsync(ExceptionContext context)
    {
        StringBuilder sb = new();
        sb.AppendLine("Exception：");
        sb.AppendLine(context.Exception.Message);
        sb.AppendLine(context.Exception.StackTrace);
        if (context.Exception.InnerException != null)
        {
            sb.AppendLine("InnerException：");
            sb.AppendLine(context.Exception.InnerException.Message);
            sb.AppendLine(context.Exception.InnerException.StackTrace);
        }
        _logger.LogError("{}", sb.ToString());
        context.Result = ApiResult.Ok(500, "系统错误");
        await Task.CompletedTask;
    }
}